<script setup>
import { ref, reactive, toRaw } from "vue";
import { Upload, message } from "ant-design-vue";
let props = defineProps({
  id: {
    type: String,
    default: "",
  },
  maxCount: {
    type: Number,
    default: 5,
  },
  fileSize: {
    type: Number,
    default: 5,
  },
});

const uploadImgUrl = ref(
  "https://mastertracktires.com/tires_proxy/common/upload"
);
const emit = defineEmits(["handleFilesChange"]);
let fileList = ref([]);

const handleChange = (info) => {
  if (info.file.status !== "uploading") {
    let curFileList = toRaw(info.fileList);
    let images = [];
    curFileList.forEach((item) => {
      if (item.response.data.fileUrl) {
        images.push(item.response.data.fileUrl);
      }
    });
    emit("handleFilesChange", images.join(","));
  }
  if (info.file.status === "done") {
    message.success(`${info.file.name} file uploaded successfully`);
  } else if (info.file.status === "error") {
    message.error(`${info.file.name} file upload failed.`);
  }
};
const removeOne = (crtFile, files) => {
  let idx = files.findIndex((item) => item.uid == crtFile.uid);
  if (idx !== -1) {
    files.splice(idx, 1);
  }
};
const beforeUpload = (crtFile, files) => {
  if (files.length + fileList.length > props.maxCount) {
    message.warning(`File numbers not exceeding ${props.maxCount}`);
    removeOne(crtFile, files);
    return false;
  }
  const isLt2M = crtFile.size / 1024 / 1024 < props.fileSize;
  if (!isLt2M) {
    message.error(`File sizes not exceeding ${props.fileSize}MB`);
    removeOne(crtFile, files);
    return false;
  }
  return true;
};
</script>
<template>
  <div>
    <Upload
      v-model="fileList"
      :maxCount="maxCount"
      :action="uploadImgUrl"
      list-type="picture-card"
      :beforeUpload="beforeUpload"
      @change="handleChange"
    >
      <div v-if="fileList.length < maxCount">
        <div style="font-size: 2rem">+</div>
      </div>
    </Upload>
    <div
      class="text-f-Montserrat-Regular ps-1"
      style="color: #9e9e9e; font-size: 16px"
    >
      Supports JPG and PNG formats, with file sizes not exceeding
      {{ fileSize }}MB and file numbers not exceeding {{ maxCount }}
    </div>
  </div>
</template>
<style scoped>
::v-deep.ant-upload-wrapper.ant-upload-picture-card-wrapper
  .ant-upload.ant-upload-select {
  background: #fff !important;
}
</style>
